<template>
    <div>
        <div class="op-div">
            <div class="arrow-div">
                <div @click="lastPage">上一页</div>
                <div>{{ state.pageNum }} / {{ state.numPages }}</div>
                <div @click="nextPage">下一页</div>
            </div>
        </div>
        <vue-pdf-embed :source="state.source" class="vue-pdf-embed" :page="state.pageNum" />
    </div>
</template>

<script setup>
import { createLoadingTask } from "vue3-pdfjs";
import VuePdfEmbed from "vue-pdf-embed";

const state = reactive({
    source: '', //预览pdf文件地址
    pageNum: 1, //当前页面 
    scale: 1, // 缩放比例
    numPages: 0, // 总页数
});

const props = defineProps({
    pdfUrl: {
        type: String
    }
})

watch(() => props.pdfUrl, value => setFilePath())

const setFilePath = () => {
    state.source = props.pdfUrl || ''
    console.log('pdf 文件变化 = ', props.pdfUrl)
}

setFilePath()

onMounted(() => {
    // 加载异步任务
    const loadingTask = createLoadingTask(state.source);
    // 载入pdf后获取页数
    loadingTask.promise.then((pdf) => {
        state.numPages = pdf.numPages;
    });
})


// 获取上一页
function lastPage() {
    if (state.pageNum > 1) {
        state.pageNum--
    }
}

// 获取下一页
function nextPage() {
    if (state.pageNum < state.numPages) {
        state.pageNum++
    }
}

</script>

<style lang="scss" scoped>
.op-div {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
    height: 50px;
    background: #fff;
}

.arrow-div {
    display: flex;
    cursor: pointer;

    div {
        width: 100px;
        height: 35px;
        line-height: 35px;
        text-align: center;
        margin: 0 15px;
        border: 1px solid #ddd;
        border-radius: 5px;

        &:hover {
            background: #f8f8f8;
        }
    }
}

.vue-pdf-embed {
    text-align: center;
}
</style>
  